package com.zg.generator.web;

import java.io.File;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.R;
import com.zg.common.core.dao.generator.GenTmpl;
import com.zg.common.core.dao.generator.GenTmplDao;
import com.zg.generator.config.EngineConfig;
import com.zg.generator.service.EngineService;
import com.zg.generator.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Zxb
 */
@RestController
@AllArgsConstructor
@Api(tags = {"代码生成器"})
public class GenerateController {
    private GenTmplDao tmplDao;
    private EngineService engineService;

    @ApiOperation("生成实体")
    @PostMapping("/code/generate")
    public R<?> generate(@RequestBody GenerateVo param) {
        String schema = param.getSchema();
        String tableName = param.getTableName();
        String packageName = param.getPackageName();
        String vueLocation = param.getVueLocation();
        List<String> tmplCodeList = param.getTmpls();
        List<GenTmpl> tmplList = tmplDao.list(
                new LambdaQueryWrapper<GenTmpl>()
                        .in(GenTmpl::getCode, tmplCodeList)
        );
        File f = new File(vueLocation);

//        if (!f.exists()) {
//            return R.error("未找到前端代码路径");
//        }

        File vueFolder = new File(vueLocation + File.separator + tableName.toLowerCase());
        if (!vueFolder.exists()) {
            vueFolder.mkdirs();
        }

        String location = vueFolder.getPath();
        EngineConfig.vueLocation.set(location);
        EngineConfig.packageName.set(packageName);
        engineService.generateCode(schema, tableName, tmplList);
        return R.success();
    }
}
